package com.abc.robot01.vivemodel

import android.util.Log
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.RetrofitService.CommodityBrand
import com.abc.robot01.retrofit.bean.Condition
import com.abc.robot01.retrofit.bean.FetchDataRequest9
import com.abc.robot01.retrofit.bean.HouseType
import com.abc.robot01.retrofit.bean.Item7
import com.abc.robot01.retrofit.bean.Item71
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import org.json.JSONObject


class FangAnKuViewModel : BaseViewModel() {

    val TAG = "FangAnKuViewModel"

    val showPopup =  mutableStateOf(false)

    val loading =  mutableStateOf(false)

    val selected20 =  mutableStateOf("请选择")

    val expanded2 =  mutableStateOf(false)

    //当前选择的户型
    val selectedHouseType = mutableStateOf("")


    val show =  mutableStateOf(true)
    val selected10 =  mutableStateOf("")

    // MutableStateFlow 用来保存当前的列表状态
    private val _questionList = MutableStateFlow<List<Item7>>(emptyList())
    val questionList: StateFlow<List<Item7>> = _questionList

    //输入框查询结果
    private val _questionList2 = MutableStateFlow<List<Item71>>(emptyList())
    val questionList2: StateFlow<List<Item71>> = _questionList2

    //喜好
    private val _question2List = MutableStateFlow<List<HouseType>>(emptyList())

    val question2List: StateFlow<List<HouseType>> = _question2List

    //房屋类型
    private val _question3List = MutableStateFlow<List<HouseType>>(emptyList())
    val question3List: StateFlow<List<HouseType>> = _question3List

    //风格
    private val _question4List = MutableStateFlow<List<HouseType>>(emptyList())
    val question4List: StateFlow<List<HouseType>> = _question4List

    //硬装标准
    private val _question5List = MutableStateFlow<List<HouseType>>(mutableListOf(HouseType()))
    val question5List: StateFlow<List<HouseType>> = _question5List

    //方案标签
    private val _question6List = MutableStateFlow<List<CommodityBrand>>(emptyList())
    val labelList: StateFlow<List<CommodityBrand>> = _question6List

//    //当前选择的硬装标准
//    val selectedDesigner = mutableStateOf("")

    /**
     * 当前是否是公库.
     * */
    val isPublic = mutableStateOf(false)

    //名称
    val name = mutableStateOf("")



    //喜好
    val interestsCodeList2 = mutableStateListOf<ButtonState>()

    val interests = mutableStateOf("全部")

    //风格
//    val styleCode = mutableStateOf("")
    val style = mutableStateOf("全部")

    //房屋类型
    val houseTypeList = mutableStateListOf<ButtonState>()
    val styleCodeList = mutableStateListOf<ButtonState>()

    //标签
    val labeIdList = mutableStateListOf<ButtonState>()

    val style2 = mutableStateOf("全部")

    fun reset() {
        interests.value = "全部"
        style.value = "全部"
        style2.value = "全部"

        repeat(interestsCodeList2.size){
            interestsCodeList2[it]= interestsCodeList2[it].copy(isSelected = false)
        }

        repeat(labeIdList.size){
            labeIdList[it]= labeIdList[it].copy(isSelected =false)
        }

        repeat(houseTypeList.size){
            houseTypeList[it]= houseTypeList[it].copy(isSelected =false)
        }

        repeat(styleCodeList.size){
            styleCodeList[it]= styleCodeList[it].copy(isSelected =false)
        }

//        interestsCodeList2.forEach {
//            it.isSelected=false
//        }
//        labeIdList.forEach {
//            it.isSelected=false
//        }

//        houseTypeList.forEach {
//            it.isSelected=false
//        }
//        .forEach {
//            it.isSelected=false
//        }


        selected20.value= "请选择"
    }

    // 模拟网络分批返回数据的函数
    fun loadData(
        isPublic2: Boolean = isPublic.value,
        interests2: String = interestsCodeList2.filter { it.isSelected }.joinToString(separator = ",") { it.code },
        style: String = styleCodeList.filter { it.isSelected }.joinToString(separator = ",") { it.code },
        useTypeCodes: String =  houseTypeList.filter { it.isSelected }.joinToString(separator = ",") { it.code },
        label: String = labeIdList.filter { it.isSelected }.joinToString(separator = ",") { it.code },
    ) {
        Log.e(TAG, "是否公库:$isPublic2")
        Log.e(TAG, "名称:${name.value}")
        Log.e(TAG, "喜好:$interests2")
        Log.e(TAG, "选择户型:$useTypeCodes")
        Log.e(TAG, "风格:$style")
        Log.e(TAG, "硬装标准:${selected20.value}")
        Log.e(TAG, "标签:${label}")

//        硬装标准
        var  a =""
        question5List.value.find {  it.name == selected20.value}?.let {
            Log.e(TAG, "硬装标准:${it}")
            a = it.code
        }
        Log.e(TAG, "硬装标准:${a}")

        viewModelScope.launch {
            loading.value = true
            _questionList.value = emptyList()
            val result = RetrofitService.instance.getDesignPackages(
                userId = Robot.userId,
                companyId = Robot.companyId,
                accessToken = Robot.accessToken, request = FetchDataRequest9(
                    condition = Condition(
                        isPublic = isPublic2,
                        name = name.value,
                        interests = interests2,
                        styles = style,
                        useTypeCodes = useTypeCodes,
                        yzPriceRange =a,
                        labelId = label,
                    )
                )
            ).string()

            Log.e(TAG, "getDesignPackages:  result:$result")
            val jsonObject2 = JSONObject(result)
            if (jsonObject2.getInt("code") == 200) {
                val data = jsonObject2.getJSONObject("data");
                val array = data.getJSONArray("list")
                repeat(array.length()) {
                    val item = array.getJSONObject(it);
                    Log.e(TAG, "getDesignPackages:  item:$item")
                    val name = item.getString("name")
                    val id = item.getString("id")
                    val price = item.getString("price")
                    val thumbnail = item.getString("thumbnail")
                    val renderUrl = item.getString("renderUrl")
                    Log.e(TAG, "name:$name")
                    _questionList.value += Item7(
                        id = id,
                        name = name,
                        price = price,
                        thumbnail = thumbnail,
                        renderUrl = renderUrl
                    )
                }
            }
            loading.value = false
        }
    }

    fun loadData2() {
        viewModelScope.launch {
            //标签
            Log.e(TAG, "开始查询方案标签")
            val s8 = RetrofitService.instance.getLabelList(
                accessToken = Robot.accessToken,
                companyId = Robot.companyId,
                type = "DESIGN_PACKAGE"
            )
            s8.data.forEach {
                Log.e(TAG, "方案标签:${it.name}")
            }
            _question6List.value = s8.data
            Log.e(TAG, "方案标签:$s8")

            s8.data.forEach {
                labeIdList.add(ButtonState(it.name,it.id,false))
            }
            Log.e(TAG, "喜好")
            val s = RetrofitService.instance.getSysDicByType(
                accessToken = Robot.accessToken,
                type = "INTEREST"
            )
            Log.e(TAG, "喜好:"+s)
            _question2List.value = s.data

            s.data.forEach {
                Log.e(TAG, "喜好:"+it)
                interestsCodeList2.add(ButtonState(label = it.name, code= it.code, isSelected = false))
            }

            Log.e(TAG, "房屋类型")
            val s2 = RetrofitService.instance.getSysDicByType(
                accessToken = Robot.accessToken,
                type = "JPFA_SYLX"
            ).also {
                Log.e(TAG, "房屋类型 size:" + it.data.size)
                Log.e(TAG, "房屋类型:${it.data}")
            }
            _question3List.value += s2.data

            s2.data.forEach {
                Log.e(TAG, "房屋类型:"+it)
                houseTypeList.add(ButtonState(label = it.name, code= it.code, isSelected = false))
            }

            Log.e(TAG, "风格")
            val s1 = RetrofitService.instance.getSysDicByType(
                accessToken = Robot.accessToken,
                type = "STYLE"
            )
            _question4List.value += s1.data
            Log.e(TAG, "风格 size:" + s1.data.size)
            Log.e(TAG, "风格:$s1")


            s1.data.forEach {
                Log.e(TAG, "风格:"+it)
                styleCodeList.add(ButtonState(label = it.name, code= it.code, isSelected = false))
            }

            val s5 = RetrofitService.instance.getSysDicByType(
                accessToken = Robot.accessToken,
                type = "YZ_PRICE_RANGE"
            )
            _question5List.value += s5.data
            Log.e(TAG, "硬装标准:$s5")
        }
    }

    fun loadData3(
        name:String,
        isPublic2: Boolean = isPublic.value,
    ) {
        Log.e(TAG, "是否公库:$isPublic2")
        if(name.trim()=="")
        {
            return
        }
//        Log.e(TAG, "名称:${name.value}")
        viewModelScope.launch {
//            loading.value = true
            _questionList2.value = emptyList()
            val result = RetrofitService.instance.getDesignPackages(
                userId = Robot.userId,
                companyId = Robot.companyId,
                accessToken = Robot.accessToken, request = FetchDataRequest9(
                    condition = Condition(
                        isPublic = isPublic2,
                        name = name,
                    )
                )
            ).string()
            val jsonObject2 = JSONObject(result)
            if (jsonObject2.getInt("code") == 200) {
                val data = jsonObject2.getJSONObject("data");
                val array = data.getJSONArray("list")
                repeat(array.length()) {
                    val item = array.getJSONObject(it);
                    Log.e(TAG, "getDesignPackages:  item:$item")
                    val name = item.getString("name")
                    val id = item.getString("id")
                    Log.e(TAG, "name:$name")
                    _questionList2.value += Item71(
                        id = id,
                        name = name,
                    )
                }
            }
            if(_questionList2.value.size >0){
                show.value =true
            }
            Log.e(TAG, "loadData3:  result:${_questionList2.value}")
        }
    }


}

data class ButtonState(var label: String, var code:String, var isSelected: Boolean)

